var api = require('../../../utils/api.js');
var util = require('../../../utils/util.js');
var md = require('../../../utils/md5.js');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: "",
    verifyCodeNumber: "",
    pwd: "",
    verifyCode: "获取验证码",
    is_disable: false,
    joinStatus: 0,

    discount: "",
    shopuserid: "",
    shop_id: "",
    linkCode: "",
    is_open: "",

    login_code: "",
    login_encryptedData: "",
    login_iv: "",
    verifyDisabled: true,
    confirmDisabled: true,
    hiddenForm: true,
    hiddenConfirmBtn: false,
    showLogin: false,
  },

  onLoad: function(options) {
    var that=this;
    if (options.q) {
      var page = decodeURIComponent(options.q);
      var strs = page.split("?"); //字符分割 
      strs = strs[1];
      var params = strs.split('&');

      var shopids = params[1];
      var shopdiscounts = params[2];
      var opens = params[3];
      var shopuserids = params[4];
      var linkCodes = params[5];

      this.setData({
        shop_id: shopids.split("=")[1],
        discount: shopdiscounts.split("=")[1],
        shopuserid: shopuserids.split("=")[1],
        linkCode: linkCodes.split("=")[1],
        is_open: opens.split("=")[1]
      })
    } else {
      this.setData({
        shop_id: options.shop_id,
        discount: options.discount,
        shopuserid: options.shopuserid,
        linkCode: options.linkCode,
        is_open: options.is_open
      })
    }
    var accountInfo = app.globalData.accountInfo;
    var isLogin = wx.getStorageSync("isLogin");
    if (isLogin && accountInfo.type == 3) {
      setTimeout(function() {
        wx.reLaunch({
          url: '../../sales/sales',
        })
      }, 1000);
    } else {
      //判断是否授权登录
      wx.getSetting({
        success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            that.autoLogin();
          } else {
            that.setData({
              showLogin: true
            })
          }
        }
      })
    }
  },

  //登录
  autoLogin: function() {
    var that = this;
    wx.login({
      success: function (res_login) {
        if (res_login.code) {
          wx.getUserInfo({
            withCredentials: true,
            success: function(res_user) {
              that.setData({
                login_code: res_login.code,
                login_encryptedData: res_user.encryptedData,
                login_iv: res_user.iv
              });
              that.login_request();
            },
            fail: function(fail_res) {
              if (fail_res.errMsg == "getUserInfo:fail auth deny") {
               
              }
            }
          })
        }
      }
    })
  },

  //请求后台登录
  login_request: function() {
    var that = this;
    var params = new Object()
    params.code = that.data.login_code;
    params.encryptedData = that.data.login_encryptedData;
    params.iv = that.data.login_iv;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'waiter/login',
      success: function(res) {
        if (res.data.code) {
          if (res.data.code == '2499') {
            wx.showModal({
              title: '提示',
              content: '请前往已绑定的微信登录;如需解绑或其他问题请联系客服',
              confirmText: '好',
              cancelText: '联系客服',
              success: function(suress) {
                if (!suress.confirm) {
                  wx.makePhoneCall({
                    phoneNumber: app.globalData.service_phone, //此号码并非真实电话号码，仅用于测试
                  })
                }
              }
            })
          } else if (res.data.code == '5802') {
            util.showError("密码错误");
          } else if (res.data.code == '2400') {
            util.showError('账号不存在');
          } else {
            util.showError(res.data.message);
          }

        } else {
          that.setData({ showLogin: false});
          app.globalData.loginState = 1;
          wx.setStorageSync("isLogin", "1");
          app.globalData.accountInfo = res.data.data.result;
          that.joinForeman();
        }
      },
      fail: function(fail) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  //加入店员
  joinForeman: function() {
    var that = this;
    var params = new Object()
    params.shop_user_id = that.data.shopuserid;
    params.shop_id = that.data.shop_id;
    params.linkCode = that.data.linkCode;

    api.POST({
      params: params,
      url: app.globalData.base_url +'waiter/addInfo',
      success: function(res) {
        console.log('加入店员', res)
        if (res.data.code) {
          util.showError(res.data.message);
          return;
        }

        that.setData({
          shopName: res.data.data.shop_name,
          avatar: res.data.data.avatar,
          joinStatus: res.data.data.status,
          hiddenForm: res.data.data.status != 0,
          hiddenConfirmBtn: res.data.data.status == 1,
        })
        that.refreshUI();
      },
      fail: function(fail) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },


  bindPhoneInput: function(e) {
    var phone = e.detail.value;
    this.setData({
      phone: phone
    })
    if (this.data.phone) {
      this.setData({
        verifyDisabled: false,
      });
    }
    this.adjustConfirmBtn();
  },
  bindPwdInput: function(e) {
    this.setData({
      pwd: e.detail.value
    })
    this.adjustConfirmBtn();
  },
  bindVerifyInput: function(e) {
    this.setData({
      verifyCodeNumber: e.detail.value
    })
    this.adjustConfirmBtn();
  },

  adjustConfirmBtn: function() {
    if (this.data.phone && this.data.pwd && this.data.verifyCodeNumber) {
      this.setData({
        confirmDisabled: false
      });
    }
  },

  refreshUI: function() {
    var isLogin = wx.getStorageSync("isLogin");
    if (!util.isEmpty(isLogin) && this.data.joinStatus == 1) {
      setTimeout(function() {
        wx.reLaunch({
          url: '../../sales/sales',
        })
      }, 2000);
      return;
    }
  },


  // 发送验证码
  sendVerifyCode: function(e) {
    var that = this;
    var isphone = util.validateMobile(that.data.phone);
    if (!isphone) {
      util.showError('请输入正确的手机号')
      return;
    }

    var params = new Object()
    params.mobile = that.data.phone;
    params.type = '8';

    util.showLoading("验证码发送中...");
    api.POST({
      params: params,
      url: app.globalData.verifyCode_url,
      success: function(res) {
        util.hiddenLoading();
        if (res.data.code) {
          util.showError(res.data.message);
        } else {
          var total_micro_second = 60 * 1000;
          that.setData({
            verifyDisabled: true
          })
          //验证码倒计时
          count_down(that, total_micro_second);
          wx.showModal({
            title: '提示',
            content: '发送验证码成功！',
            showCancel: false
          })
        }
      },
      fail: function(fail) {
        util.hiddenLoading();
        util.showError("网络错误，请检查网络。");
      }
    })
  },

  // 提交
  confirmClick: function(e) {
    var that = this;
    var isphone = util.validateMobile(that.data.phone);
    if (!isphone) {
      util.showError('请输入正确的手机号');
      return;
    }
    if (util.isEmpty(that.data.pwd)) {
      util.showError('请输入密码');
      return;
    }
    if (!util.checkRate(that.data.pwd)) {
      util.showError('密码只能有字母和数字组成');
      return;
    }
    if (that.data.pwd.length < 8) {
      util.showError('密码至少8位');
      return;
    }
    if (!that.data.verifyCodeNumber) {
      util.showError('请输入验证码');
      return;
    }

    var params = new Object()
    params.mobile = that.data.phone;
    params.shop_id = that.data.shop_id;
    params.password = md(that.data.pwd);
    params.discount = that.data.discount;
    params.captcha = that.data.verifyCodeNumber;
    params.linkCode = that.data.linkCode;
    params.is_open = that.data.is_open;

    api.POST({
      params: params,
      url: app.globalData.waiterSubmit_url,
      success: function(res) {
        if (res.data.status == 0) {
          util.showError(res.data.message);
          return;
        }

        app.globalData.accountInfo = '';
        that.setData({
          joinStatus: 1,
          confirmDisabled: false,
          hiddenForm: true,
          hiddenConfirmBtn: true,
        })
        setTimeout(function() {
          wx.switchTab({
            url: '../../sales/sales'
          })
        }, 2000);
      },
      fail: function(fail) {
        util.showError("网络错误，请检查网络。");
      }
    })
  },
})



/* 毫秒级倒计时 */
function count_down(that, total_micro_second) {
  if (total_micro_second <= 0) {

    that.setData({
      verifyCode: "重新发送",
      verifyDisabled: false,

    });
    // timeout则跳出递归
    return;
  }
  // 渲染倒计时时钟
  that.setData({
    verifyCode: date_format(total_micro_second) + " 秒",
    verifyDisabled: true,

  });
  setTimeout(function() {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that, total_micro_second);
  }, 10)
}
// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60)); // equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}